// pages/card/card.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        StatusBar: app.globalData.StatusBar,
        CustomBar: app.globalData.CustomBar,
        carInfo: {
            cid: '',
        },
        auctionInfo: {
            auctionId: ''
        },
        dealerInfo: {},
        userInfo: {},
        seeImages: false,
        imageList: [],
        imageIndex: 0,
        modalName: null, // 
        getFocusByPrice: false,
        subPrice: {
            price: '',
            label: '',
        },
        labelList: [{
            name:'加500元',
            number: 500
        },{
            name:'加1000元',
            number: 1000
        },{
            name:'加2000元',
            number: 2000
        },{
            name:'加5000元',
            number: 5000
        }],
        labelApplyList:['诚心想要','等你还价','先看再买','在线等回'],
        userAgreement: true,
        auctionTimer: null,
        newOfferTimer: null,
        seeAllRep: false,
        orderInfo: {
            orderNo: '',
            payInfo: {}
        },
        nowCurrent:0,
        reporType:{
          'c300InsuranceReport':'车300碰撞保险记录',
          'c300MtnceReport':'车300保养维修记录',
          'cbsInsuranceReport':'查博士碰撞保险记录',
          'cbsMtnceReport':'查博士保养维修记录'
        },
        applyReportType:'',
    },

        // 分享车辆
        openShare(){
            this.showShareModal();
        },
      showShareModal(){
        // 请求小程序二维码
        app.sHttp.shareqrCode({pageUrl:'pages/card/auction/auction',scene:'aid='+this.data.auctionInfo.auctionId+'&bsid='+this.data.userInfo.userId}).then(res =>{
            this.selectComponent('#posterComponent').showShareModal(res.base64);
        },err=>{
          app.error(err.msg);
        });
      },
        
      // 下载车辆素材
      downLoadCarImg(e){
          let index = 0;
          this.data.seeImages?index = this.data.imageIndex : index = this.data.nowCurrent;
        //   let imagePath = this.data.carInfo.carPicList[index].picUrl;
          let self = this;
          wx.showModal({
            title: '提示',
            content: '您确定下载当前图片包吗？共' + self.data.carInfo.carPicList.length +'张图片。',
            success (res) {
                if (res.confirm) {
                  let imageList = self.data.carInfo.carPicList;
                  wx.showLoading({
                    title: '下载素材中',
                    mask: true //默认蒙层。防止触摸穿透
                  });
                  imageList.forEach((item,index) =>{
                    self.downLoadNetImage(item.picUrl,index,self.data.carInfo.carPicList.length);
                  })
                }
            }
          })
        },
        downLoadNetImage(path,index,allLong){
          wx.showLoading({
            title: '下载素材中',
            mask: true //默认蒙层。防止触摸穿透
          })
          wx.downloadFile({
            url: path,
            success: function (res) {
              wx.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success () {
                    if(index+1 >= allLong){
                      wx.hideLoading()
                      app.alert("全部素材已保存到您的手机")
                      wx.hideLoading();
                    }
                },
                fail () {
                  wx.hideLoading()
                  app.alert("保存失败")
                }
              })
            }
          })
        },
        carImageChange(e){
          this.setData({
            'nowCurrent': e.detail.current
          })
        },
    /**
     * 生命周期函数--监听页面加载
     */
    doNothing(){},
    onLoad: function (options) {
        // 必须一个拍卖的ID
        let aid = null;
        if(undefined != options.aid){
            aid = options.aid;
        }else if(options.scene){
            let scanData = decodeURIComponent(options.scene);
            aid = app.GetQueryString(scanData,'aid');
            var value = wx.getStorageSync('user_bsid');
            if(value != undefined && value != 'undefined' && value != null && value != 'null' && value != ''){ 
              app.globalData.shareUserId = value;
            }else{
                if(app.GetQueryString(scanData,'bsid')){
                  wx.setStorageSync('user_bsid', app.GetQueryString(scanData,'bsid'));
                  app.globalData.shareUserId = app.GetQueryString(scanData,'bsid');
                }else{
                    // 当前小程序码已过期，请重新生成海报
                  wx.showModal({
                    title: '海报过期提醒',
                    content: '当前小程序码已过期，请重新生成海报',
                    confirmText: '我知道啦',
                    showCancel: false,
                    success(res) {
                    }
                  })
                }
            }
        }
        if(aid){
        let self = this;
        this.setData({
            'auctionInfo.auctionId': aid
        },()=>{
            self.InitUserStatus();
        })
        }else{
        app.showNoAuthOrNoGrant('未找到您要查看的拍卖信息');
        }
    },

    copyRecommendReasons(){
        let recommendReasons = this.data.carInfo.recommendReasons;
        wx.setClipboardData({
          data: recommendReasons,
          success: function (res) {
            wx.getClipboardData({
              success: function (res) {
                wx.showToast({
                  title: '已为您复制推荐理由',
                  icon:'none'
                })
              }
            })
          }
        })
    },
    // 检查一下登录状态。
    async InitUserStatus() {
        app.showLoading("获取用户信息");
        await app.checkToken();
        this.InitUserInfo();
        wx.hideLoading();
    },
    InitUserInfo() {
        this.setData({
            'userInfo': app.globalData.userInfo
        });
        app.sHttp.auctionView(this.data.auctionInfo.auctionId).then(res => {
            let imageList = [];
            res.result.carInfo.carPicList.forEach(item => {
                imageList.push(item.picUrl);
            })
            if(res.result.carInfo.insuranceReportType || res.result.carInfo.mtnceReportType){
              res.result.carInfo.haveReport = true;
            }else{
              res.result.carInfo.haveReport = false;
            }
            // 处理两个时间，
            res.result.carInfo.licensingTime = this.handleTimesForRI(res.result.carInfo.licensingTime || '');
            res.result.carInfo.compulsoryInsuranceTime = this.handleTimesForRI(res.result.carInfo.compulsoryInsuranceTime);
            res.result.carInfo.yearlyInspectionTime = this.handleTimesForRI(res.result.carInfo.yearlyInspectionTime);
            // res.result.auctionInfo.endTime = '2021-10-27 00:00:00';
            // res.result.auctionInfo.status = 3;
            // res.result.auctionInfo.isPayDepositAmount = 0;
            if(res.result.auctionInfo.offerList){

            }else{
                res.result.auctionInfo.offerList = []
            }
            this.setData({
                'imageList': imageList,
                'carInfo': res.result.carInfo,
                'dealerInfo': res.result.dealerInfo,
                'auctionInfo': res.result.auctionInfo
            })
            this.handleTimer();
            this.handleOffer();
        }, err => {
            app.error(err.msg);
            let self = this;
            setTimeout(() => {
                self.BackPage();
            }, 1500);
        })
    },
    handleOffer(){
        if (3 == this.data.auctionInfo.status) {
            // 销毁所有的定时器。
            if (this.data.newOfferTimer) {
                clearInterval(this.data.newOfferTimer);
            }
            var that = this
            let newOfferTimer = setInterval(that.auctionLatestOffer, 5000);
            this.setData({
                'newOfferTimer': newOfferTimer
            })
        }
    },
    // 定时查询 最新的出价信息。
    auctionLatestOffer(){
        if(3 == this.data.auctionInfo.status){
            app.sHttp.auctionLatestOffer({auctionId:this.data.auctionInfo.auctionId,currentPrice:this.data.auctionInfo.currentPrice}).then(res => {
                let offerList = this.data.auctionInfo.offerList;
                if(res.result){
                    if(res.result.offerList){
                        res.result.offerList = res.result.offerList.concat(offerList);
                    }
                }
                if(res.result){
                    this.setData({
                        'auctionInfo.currentPrice': res.result.currentPrice,
                        'auctionInfo.offerList': res.result.offerList
                    })
                }
            }, err => {           
                //  报错了。
                if(this.data.newOfferTimer){
                    clearInterval(this.data.newOfferTimer);
                }
            })
        } 
    },
    // 计算倒计时。
    handleTimer() {
        if (3 == this.data.auctionInfo.status) {
            // 销毁所有的定时器。
            if (this.data.auctionTimer) {
                clearInterval(this.data.auctionTimer);
            }
            var that = this
            this.setData({
                'auctionInfo.time': that.queryTime(that.data.auctionInfo.endTime)
            })
            this.setCountDown();
            let auctionTimer = setInterval(that.setCountDown, 1000);
            this.setData({
                'auctionTimer': auctionTimer
            })
        }
    },
    /**
     * 倒计时
     */
    setCountDown: function () {
        if (3 == this.data.auctionInfo.status) {
            let time = 1000;
            let auctionInfo = this.data.auctionInfo;
            if (auctionInfo.time <= 0) {
                auctionInfo.time = 0;
            }
            let formatTime = this.getFormat(auctionInfo.time);
            auctionInfo.time -= time;
            auctionInfo.countDownHH = formatTime.hh;
            auctionInfo.countDownMM = formatTime.mm;
            auctionInfo.countDownSS = formatTime.ss;
            this.setData({
                'auctionInfo': auctionInfo
            });
        }
    },
    getFormat(msec) {
        let ss = parseInt(msec / 1000);
        let ms = parseInt(msec % 1000);
        let mm = 0;
        let hh = 0;
        if (ss > 60) {
            mm = parseInt(ss / 60);
            ss = parseInt(ss % 60);
            if (mm > 60) {
                hh = parseInt(mm / 60);
                mm = parseInt(mm % 60);
            }
        }
        ss = ss > 9 ? ss : `0${ss}`;
        mm = mm > 9 ? mm : `0${mm}`;
        hh = hh > 9 ? hh : `0${hh}`;
        return {
            ss,
            mm,
            hh
        };
    },
    queryTime(pintime) {
        var start_date = new Date();
        var end_date = new Date(pintime.replace(/-/g, "/"));
        var days = end_date.getTime() - start_date.getTime();
        console.log("获取到时间差" + days)
        return days;
    },
    handleTimesForRI(time) {
        if (time.indexOf('日') != -1 && time.indexOf('月') != -1) {
            return time.substring(0, time.indexOf('月') + 1);
        }
        return time;
    },
    BackPage() {
        var that = this;
        wx.navigateBack({
            delta: 1,
            fail: function () {
                that.toHome();
            }
        });
    },
    toHome() {
        wx.reLaunch({
            url: '/pages/home/home',
        })
    },
    doNothing(e) {},
    switchSeeImage(e) {
        let imageIndex = e.currentTarget.dataset.idx;
        let self = this;
        this.setData({
            'imageIndex': imageIndex,
            'seeImages': !self.data.seeImages
        })
    },
    seeImgeChange(e) {
        this.setData({
            'imageIndex': e.detail.current
        })
    },
    showModal(e) {
        this.setData({
            modalName: e.currentTarget.dataset.target
        })
    },
    hideModal(e) {
        this.setData({
            'modalName': null,
            'getFocusByPrice': false
        })
    },
    changeIcon(e) {
        let price = parseFloat(this.data.auctionInfo.currentPrice*10000) + parseFloat(Number(e.currentTarget.dataset.item));
        this.setData({
            'subPrice.label': e.currentTarget.dataset.item,
            'subPrice.price': price
        })
    },
    publishInput(e) {
        this.setData({
            'subPrice.price': e.detail.value,
            'subPrice.label': ''
        })
    },
    useUserAgreement() {
        this.setData({
            userAgreement: !this.data.userAgreement
        })
    },
    goOptions() {
        // 参与竞拍的前置。
        if (3 != this.data.auctionInfo.status) {
            app.alert('竞拍已结束');
            return;
        }
        if (1 == this.data.auctionInfo.isPayDepositAmount) {
            // 交了保证金
            this.jingjiaModal();
        } else {
            // this.jingjiaModal();
            // 没交保证金
            this.goPayDepositAmount();
        }
    },
    seeAllRep() {
        let self = this;
        this.setData({
            'seeAllRep': !self.data.seeAllRep
        })
    },
    onUnload(){
        // 销毁所有的定时器。
        if (this.data.auctionTimer) {
            clearInterval(this.data.auctionTimer);
        }
        if (this.data.newOfferTimer) {
            clearInterval(this.data.newOfferTimer);
        }
    },
    // 支付保证金一系列
    // 支付定金弹窗
    goPayDepositAmount() {
        if (2 != this.data.userInfo.accountStatus) {
            app.alert('您当前尚未注册，无法支付定金');
            return;
        }
        if (1 == this.data.auctionInfo.isPayDepositAmount) {
            app.alert('定金已支付');
            return;
        }
        this.setData({
            'modalName': 'bargain'
        })
    },
    toDoPay() {
        let auctionId = this.data.auctionInfo.auctionId;
        if (null == auctionId || undefined == auctionId || '' == auctionId) {
            app.error('未知拍卖信息');
            return;
        }
        let orderInfo = this.data.orderInfo;
        if ('' == orderInfo.orderNo || undefined == orderInfo.payInfo.paySign) {
            app.sHttp.auctionOrderCreate(auctionId).then(res => {
                let self = this;
                this.setData({
                    'orderInfo.orderNo': res.result.orderNo,
                    'orderInfo.payInfo': res.result.payInfo
                }, () => {
                    self.hideModal();
                    self.tuneUpPay();
                });
            }, err => {
                app.error(err.msg);
            })
        } else {
            this.hideModal();
            this.tuneUpPay();
        }
    },
    tuneUpPay() {
        // 从Data里面拿参数
        let orderInfo = this.data.orderInfo;
        if ('' == orderInfo.orderNo || undefined == orderInfo.payInfo.paySign) {
            app.alert('支付参数不完整');
            return;
        };
        // 吊起支付。
        let self = this;
        wx.requestPayment({
            timeStamp: orderInfo.payInfo.timeStamp,
            nonceStr: orderInfo.payInfo.nonceStr,
            package: orderInfo.payInfo.package,
            signType: orderInfo.payInfo.signType,
            paySign: orderInfo.payInfo.paySign,
            success(res) {
                // 查询订单完成信息。
                let _this = self;
                app.showLoading('查询订单状态');
                setTimeout(() => {
                    wx.hideLoading();
                    _this.auctionOrderPayResult();
                }, 5000);
            },
            fail(res) {
                app.alert('您已取消支付，可点击立即支付重新支付');
            }
        })
    },
    auctionOrderPayResult() {
        let orderInfo = this.data.orderInfo;
        if ('' == orderInfo.orderNo) {
            app.alert('支付参数不完整');
            return;
        };
        app.sHttp.auctionOrderPayResult(orderInfo.orderNo).then(res => {
            let orderStatus = res.orderStatus;
            if (0 == orderStatus) {
                this.wxShowModal('查询结果', '请等待几分钟后重新进入查看是否支付成功，如长时间未显示未支付成功状态，请联系客服处理', 0);
                return;
            }
            if (1 == orderStatus) {
                this.wxShowModal('支付成功', '您已支付成功', 1);
                return;
            }
        }, err => {
            app.error(err.msg);
        })
    },
    wxShowModal(title, content, orderStatus) {
        let self = this;
        wx.showModal({
            title: title,
            content: content,
            confirmText: '我知道了',
            showCancel: false,
            success(res) {
                self.setData({
                    'modalName': null,
                    'getFocusByPrice': false
                })
                // 重载全部接口信息
                self.InitUserInfo();
            }
        })
    },
    // 竞价出价一系列的
    jingjiaModal(){
        this.setData({
            'modalName':'jingjia',
            'subPrice.price': ''
        });
        let self = this;
        setTimeout(() => {
            self.setData({
                'getFocusByPrice': true
            })
        }, 300);
    },
    subPrice(){
        let price = this.data.subPrice.price;
        if('' == price){
            app.alert('请出价');
            return;
        }
        if(price/10000 < parseFloat(this.data.auctionInfo.currentPrice) + parseFloat(Number(this.data.auctionInfo.markupAmount)/10000)){
            app.alert('出价小于当前价格');
            return;
        }
        // 出价
        price = price/10000
        app.sHttp.auctionOffer({auctionId:this.data.auctionInfo.auctionId,offerPrice:price}).then(res => {
            if(2 == res.result.offerResult){
                app.alert('出价失败，已有更高出价：' + res.result.currentPrice + '万元');
            }else{
                this.hideModal();
                app.alert('出价完成');
            }
            let offerList = this.data.auctionInfo.offerList;
            if(undefined != res.result.offerList){
                res.result.offerList = res.result.offerList.concat(offerList);
            }
            this.setData({
                'auctionInfo.currentPrice': res.result.currentPrice,
                'auctionInfo.offerList': res.result.offerList
            })
        }, err => {
            app.error(err.msg);
        })
    },
    seeOrapply(e){
      let url = e.currentTarget.dataset.url;
      if(url){
        app.globalData.lookReportInfoUrl = url;
        wx.navigateTo({
          url: '/pages/carQueryRecord/detailed/detailed',
        })
      }else{
        this.setData({
          'modalName':'reportApply',
          'applyReportType': e.currentTarget.dataset.type
        })
      }
    },
    goApplyReport(){
      // 申请操作。
      app.sHttp.reportApply({carId:this.data.carInfo.carId,reportType:this.data.applyReportType}).then(res=>{
        this.hideModal();
        app.alert('申请已提交,请等待回复~');
      },err=>{
        app.error(err.msg);
      })
    },
})